//
//  XDCheckWithdrawViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/3/7.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDCheckWithdrawViewController.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "AFHTTPSessionManager+POST.h"
#import "XDWithdrawProgressViewController.h"
@interface XDCheckWithdrawViewController ()<UITextFieldDelegate>

@property (nonatomic, weak) UITextField *withdrawAmtTf;

@property (nonatomic, weak) UIView *passBackView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic ,weak) UITextField *passTextField;

@property (nonatomic, weak) UIView *alertView;

@property (nonatomic, weak) UIView *failureAlert;

@property (nonatomic, weak) UIView *succeedAlert;

@property (nonatomic, assign) long withdrawalId;

@end

@implementation XDCheckWithdrawViewController

- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"提现";
    self.view.backgroundColor = kColorRGB(234, 234, 234);
    UITextField *withdrawAmtTf = [self createTextFieldWithFrame:CGRectMake(0, 10, kScreenW, 50) textFont:kBaseFont_(16) textColor: kColorRGB(51, 51, 51) placeholder:@"请输入提现金额" placeholderFont:kBaseFont_(13) leftTitle:@"提现金额" delegate:self inView:self.view tag:0];
    withdrawAmtTf.clearsOnBeginEditing = YES;
    withdrawAmtTf.keyboardType = UIKeyboardTypeNumberPad;
    self.withdrawAmtTf = withdrawAmtTf;
    
    UILabel *canWithdrawAmt = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(withdrawAmtTf.frame) + 10, kScreenW, 20)];
    if (!self.available) {
        self.available = @"0";
    }
    canWithdrawAmt.text = [NSString stringWithFormat:@"账户可用余额:%@元",self.available];
    canWithdrawAmt.textColor = kColorRGB(102, 102, 102);
    canWithdrawAmt.font = kBaseFont_(13);
    [self.view addSubview:canWithdrawAmt];
    
    UIButton *totalAmtBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenW - 75, CGRectGetMaxY(withdrawAmtTf.frame) + 10, 60, 20)];
    [totalAmtBtn setTitle:@"全部提现" forState:UIControlStateNormal];
    [totalAmtBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
    [totalAmtBtn addTarget:self action:@selector(totalAmtBtnClick) forControlEvents:UIControlEventTouchUpInside];
    totalAmtBtn.titleLabel.font = kBaseFont_(13);
    [self.view addSubview:totalAmtBtn];
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - 240) / 2, CGRectGetMaxY(withdrawAmtTf.frame) + 70, 240, 40)];
    [nextBtn setImage:[UIImage imageNamed:@"withdrawAmt"] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"提现须知"  style:UIBarButtonItemStylePlain target:self action:@selector(withdrawAmtAttention)];
    rightItem.tintColor = kColorRGB(187,147,115);
    self.navigationItem.rightBarButtonItem = rightItem;
}


//修改UITextField的placeholder字体并垂直居中
- (NSAttributedString *)textFieldAttributedPlaceholderWith:(UITextField *)textField placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont  {
    NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - placeholderFont.lineHeight) / 2.0;
    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName:placeholderFont, NSParagraphStyleAttributeName : style}];
    return attr;
}

- (UITextField *)createTextFieldWithFrame:(CGRect)frame textFont:(UIFont *)textFont textColor:(UIColor *)textColor placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont leftTitle:(NSString *)leftTitle delegate:(id)obj inView:(UIView *)inView tag:(NSInteger)tag {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    
    textField.background = [UIImage imageNamed:@"textfield-1"];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor =  textColor;
    textField.font = textFont;
    textField.tag = tag;
    
    textField.attributedPlaceholder = [self textFieldAttributedPlaceholderWith:textField placeholder:placeholder placeholderFont:placeholderFont];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 80, 48)];
    leftView.backgroundColor = [UIColor whiteColor];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 80, 48)];
    nameLb.text = leftTitle;
    nameLb.textColor = kColorRGB(102,102,102);
    nameLb.font = kBaseFont_(14);
    nameLb.textAlignment = NSTextAlignmentLeft;
    [leftView addSubview:nameLb];
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    
    textField.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 15, 48)];
    textField.rightViewMode = UITextFieldViewModeAlways;
    
    textField.delegate = obj;
    [inView addSubview:textField];
    return textField;
}


- (void)totalAmtBtnClick {
    
    NSLog(@"全部提现");
    [self.withdrawAmtTf resignFirstResponder];
    self.withdrawAmtTf.text = self.available;
    
}

- (void)nextBtnClick {
    NSLog(@"确认");
    if (!self.withdrawAmtTf.text.length) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入提现金额" view:self.view];
    }else if ([self.withdrawAmtTf.text floatValue] > [self.available floatValue]) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"提现金额不足" view:self.view];
    }else if ([self.withdrawAmtTf.text floatValue] == 0) {
        //
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"暂无提现金额" view:self.view];
    }else {
        
        [UIView animateWithDuration:0.25 animations:^{
            self.passBackView.alpha = 1;
        } completion:^(BOOL finished) {

        }];
        
    }
}

- (UIView *)passBackView {
    
    
    if (_passBackView == nil) {
        UIView *passBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        passBackView.backgroundColor = kColorRGBA(0, 0, 0, 0.5);
        passBackView.alpha = 0;
        _passBackView = passBackView;
        [self.view addSubview:passBackView];
        
        UIView *passView = [[UIView alloc] initWithFrame:CGRectMake((kScreenW - 270) * 0.5, 50, 270, 165)];
        passView.backgroundColor = [UIColor whiteColor];
        passView.layer.cornerRadius = 10;
        passView.layer.masksToBounds = YES;
        [passBackView addSubview:passView];
        
        UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(270 - 30, 15, 15, 15)];
        [closeBtn setBackgroundImage:[UIImage imageNamed:@"Plus"] forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [passView addSubview:closeBtn];
        
        UILabel *tipLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 270, 35)];
        tipLb.text = @"请输入交易密码";
        tipLb.textColor = kColorRGB(0, 0, 0);
        tipLb.textAlignment = NSTextAlignmentCenter;
        tipLb.font = kBaseFont_(15);
        [passView addSubview:tipLb];
        
        
        UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(27, CGRectGetMaxY(tipLb.frame) + 10, 216, 36)];
        
        textField.hidden = YES;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.delegate = self;
        [textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
        [textField becomeFirstResponder];
        self.passTextField =textField;
        [passView addSubview:textField];
        
        UIButton *passBtn = [[UIButton alloc] initWithFrame:CGRectMake(27, CGRectGetMaxY(tipLb.frame) + 10, 216, 36)];
        [passBtn setBackgroundImage:[UIImage imageNamed:@"passWord"] forState:UIControlStateNormal];
        [passView addSubview:passBtn];
        for (int i = 0; i < 6; i++) {
            
            
            UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(27+i*36, CGRectGetMaxY(tipLb.frame) + 10, 36, 36)];
            
            
            button.titleLabel.font = [UIFont systemFontOfSize:20.0];
            
            [button addTarget:self action:@selector(touchBegin) forControlEvents:UIControlEventTouchUpInside];
            [button setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
            
            button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            [self.dataSource addObject:button];
            
            [passView addSubview:button];
 
        }
        
        UIButton *forgetPassword = [[UIButton alloc] initWithFrame:CGRectMake(270 - 75, CGRectGetMaxY(passBtn.frame), 60, 25)];
        [forgetPassword setTitle:@"忘记密码?" forState:UIControlStateNormal];
        forgetPassword.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentRight;
        [forgetPassword setTitleColor:kColorRGB(102, 102, 102) forState:UIControlStateNormal];
        forgetPassword.titleLabel.font = kBaseFont_(11);
        [forgetPassword addTarget:self action:@selector(forgetPasswordClick) forControlEvents:UIControlEventTouchUpInside];
        [passView addSubview:forgetPassword];
        
        
    }
    return _passBackView;
}
- (void)forgetPasswordClick {
    
    NSLog(@"忘记密码");
    
}

- (void)touchBegin
{
    
    [self.passTextField becomeFirstResponder];
    
}//成为第一响应者


- (void)textFieldChange:(UITextField *)textField {
    
    NSString *text = textField.text;
    if (text.length == _dataSource.count) {
        [self checkWithdrawAccount:text];
    }
    
    
    
    for (int i = 0; i < _dataSource.count; i++) {
        
        
        UIButton *btn = [_dataSource objectAtIndex:i];
        
        
        NSString *str = @"";
        
        if (i < text.length) {
            
            
            str = [text substringWithRange:NSMakeRange(i, 1)];
            
            
        }
        
        [btn setTitle:str forState:UIControlStateNormal];
    }
    

}
- (void)checkWithdrawAccount:(NSString *)payPwd{
    
    NSDictionary * param = @{@"method":@"checkWithdrawAccount",@"payPwd":payPwd,@"withdrawAmt":self.withdrawAmtTf.text};
    
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        [UIView animateWithDuration:0.2 animations:^{
            self.passBackView.alpha = 0 ;
        } completion:^(BOOL finished) {
            [self.dataSource removeAllObjects];
            [self.passBackView removeFromSuperview];
            
        if ([responseObject[@"code"] isEqualToString:@"100000"])   {
            
            NSString *endTime = responseObject[@"result"][@"endTime"];
            self.withdrawalId = [responseObject[@"result"][@"withdrawalId"] longValue];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSDate *date = [formatter dateFromString:endTime];
            
 
            NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
            dateFmt.dateFormat = @"预计最晚yyyy年MM月dd日 HH:mm到账";
            [self succeedAlert:[dateFmt stringFromDate:date]];
            [UIView animateWithDuration:0.25 animations:^{
                self.succeedAlert.alpha = 1;
            } completion:^(BOOL finished) {
                
            }];
            
        } else if ([responseObject[@"code"] isEqualToString:@"100012"]) {
            
//          public final static String SAFEPWD_ERROR = "100012";	//交易密码错误
            
            [UIView animateWithDuration:0.25 animations:^{
                self.failureAlert.alpha = 1;
            } completion:^(BOOL finished) {
                
            }];
            
        } else {
            [UIView animateWithDuration:0.25 animations:^{
                self.failureAlert.alpha = 1;
            } completion:^(BOOL finished) {
                
            }];
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
        }
         }];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

- (void)closeBtnClick {
    
    [UIView animateWithDuration:0.25 animations:^{
    self.passBackView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.dataSource removeAllObjects];
        [self.passBackView removeFromSuperview];
    }];
}


- (void)withdrawAmtAttention {
    
     NSLog(@"提现须知");
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    NSInteger pointLength = existedLength - selectedLength + replaceLength;
    //超过6位 就不能在输入了
    if (pointLength > 6) {
        return NO;
    }else{
        return YES;
    }
    
}

- (UIView *)failureAlert{

    if (_failureAlert == nil) {
        
        UIView *alertView = [[UIView alloc] initWithFrame:kScreenB];
        alertView.alpha = 0;
        alertView.backgroundColor = kColorRGBA(0, 0, 0, 0.5);
        _failureAlert = alertView;
        [self.view addSubview:alertView];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake((kScreenW - 270 *kscaleW) * 0.5, 136 * kscale, 270 *kscaleW, 115)];
        view.backgroundColor = [UIColor whiteColor];
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        [alertView addSubview:view];
        
        UILabel *titlelb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 270 *kscaleW, 71)];
        titlelb.text = @"交易密码错误,请重试";
        titlelb.textColor = kColorRGB(0, 0, 0);
        titlelb.font = kBaseFont_(16);
        titlelb.textAlignment = NSTextAlignmentCenter;
        [view addSubview:titlelb];
        
        
        UIView *topCover = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titlelb.frame), 270 * kscaleW, 1)];
        topCover.backgroundColor = kColorRGBA(0, 0, 0, 0.2);
        [view addSubview:topCover];
        
        NSArray *btnTitleArr = @[@"忘记密码",@"重试"];
        for (NSInteger i = 0; i < btnTitleArr.count; i ++) {
            UIButton *forgetBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * 270 * kscaleW * 0.5, CGRectGetMaxY(topCover.frame), 270 * kscaleW * 0.5, 44)];
            [forgetBtn setTitle:btnTitleArr[i] forState:UIControlStateNormal];
            [forgetBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
            forgetBtn.titleLabel.font = kBaseFont_(15);
            forgetBtn.tag = 100 + i;
            [forgetBtn addTarget:self action:@selector(failureAlertClick:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:forgetBtn];
        }
      
        UIView *centerCover = [[UIView alloc] initWithFrame:CGRectMake(270 * kscaleW * 0.5, CGRectGetMaxY(topCover.frame), 1, 44)];
        centerCover.backgroundColor = kColorRGBA(0, 0, 0, 0.2);
        [view addSubview:centerCover];
        
    }
    return _failureAlert;
    
}

- (void)failureAlertClick:(UIButton *)failureBtn {
    
    if (failureBtn.tag == 100) {
        NSLog(@"忘记密码");
    } else if (failureBtn.tag == 101) {
        NSLog(@"重试");
        [UIView animateWithDuration:0.2 animations:^{
            self.failureAlert.alpha = 0;
            self.passBackView.alpha = 1;
            [self.passTextField becomeFirstResponder];
        } completion:^(BOOL finished) {
            [self.failureAlert removeFromSuperview];
        }];
    }
    
}

- (UIView *)succeedAlert:(NSString *)endTime{
    
    if (_succeedAlert == nil) {
        
        UIView *alertView = [[UIView alloc] initWithFrame:kScreenB];
        alertView.alpha = 0;
        alertView.backgroundColor = kColorRGBA(0, 0, 0, 0.5);
        _succeedAlert = alertView;
        [self.view addSubview:alertView];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake((kScreenW - 270 *kscaleW) * 0.5, 136 * kscale, 270 *kscaleW, 150)];
        view.backgroundColor = [UIColor whiteColor];
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        [alertView addSubview:view];
        
        UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake((270 - 30) *kscale , 15, 15, 15)];
        [closeBtn setBackgroundImage:[UIImage imageNamed:@"Plus"] forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(succeedcCloseBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:closeBtn];
        
        
        UILabel *titlelb = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 270 *kscaleW, 20)];
        titlelb.text = @"已提交";
        titlelb.textColor = kColorRGB(0, 0, 0);
        titlelb.font = kBaseFont_(16);
        titlelb.textAlignment = NSTextAlignmentCenter;
        [view addSubview:titlelb];
        
        
        UILabel *tipLb = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titlelb.frame) + 15, 270 *kscaleW , 15)];
        tipLb.text = @"申请已提交,请等待审核";
        tipLb.textColor = kColorRGB(102, 102, 102);
        tipLb.font = kBaseFont_(12);
        tipLb.textAlignment = NSTextAlignmentCenter;
        [view addSubview:tipLb];
        
        
        UILabel *detailLb = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(tipLb.frame) + 5, 270 *kscaleW , 15)];
//        @"预计最晚%@到账"
        detailLb.text = endTime;
        detailLb.textColor = kColorRGB(102, 102, 102);
        detailLb.font = kBaseFont_(12);
        detailLb.textAlignment = NSTextAlignmentCenter;
        [view addSubview:detailLb];
        
        UIView *topCover = [[UIView alloc] initWithFrame:CGRectMake(0, 150 - 45, 270 * kscaleW, 1)];
        topCover.backgroundColor = kColorRGBA(0, 0, 0, 0.2);
        [view addSubview:topCover];
        
       UIButton *forgetBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(topCover.frame), 270 * kscaleW, 44 * kscale)];
            [forgetBtn setTitle:@"查看提现进度" forState:UIControlStateNormal];
            [forgetBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
            forgetBtn.titleLabel.font = kBaseFont_(15);
//            forgetBtn.tag = 100 + i;
            [forgetBtn addTarget:self action:@selector(succeedAlertClick) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:forgetBtn];
//        }
//        
//        UIView *centerCover = [[UIView alloc] initWithFrame:CGRectMake(270 * kscaleW * 0.5, CGRectGetMaxY(topCover.frame), 1, 44 * kscale)];
//        centerCover.backgroundColor = kColorRGBA(0, 0, 0, 0.2);
//        [view addSubview:centerCover];
        
    }
    return _succeedAlert;
    
}

- (void)succeedcCloseBtnClick {
    
    [UIView animateWithDuration:0.25 animations:^{
        self.succeedAlert.alpha = 0;
    } completion:^(BOOL finished) {
        [self.succeedAlert removeFromSuperview];
    }];
    
}
- (void)succeedAlertClick {
    
    NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
    [df removeObjectForKey:@"toWithdraw"];
    [df synchronize];
    XDWithdrawProgressViewController *withdrawProgress = [[XDWithdrawProgressViewController alloc] init];
    withdrawProgress.wdId = self.withdrawalId;
    [self.navigationController pushViewController:withdrawProgress animated:YES];
    NSLog(@"查看提现进度");
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.withdrawAmtTf resignFirstResponder];
}
@end
